package com.forum.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.forum.dao.TokenDao;
import com.forum.entity.Token;
import com.forum.service.TokenService;
import com.forum.utils.CommonUtil;
import com.forum.utils.MyQuery;
import com.forum.utils.PageUtils;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @ClassNameTokenServiceImpl
 * @Author 张继成
 * @Date 2023/11/13 14:11
 */
@Service("tokenService")
public class TokenServiceImpl extends ServiceImpl<TokenDao, Token> implements TokenService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        Page<Token> tokenentityPage =
                this.selectPage(new MyQuery<Token>(params).getPage(), new EntityWrapper<Token>());
        return new PageUtils(tokenentityPage);
    }

    @Override
    public List<Token> selectListView(Wrapper<Token> wrapper) {
        return baseMapper.selectListView(wrapper);
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params, Wrapper<Token> wrapper) {
        Page<Token> page =new MyQuery<Token>(params).getPage();
        page.setRecords(baseMapper.selectListView(page,wrapper));
        PageUtils pageUtil = new PageUtils(page);
        return pageUtil;
    }

    @Override
    public String generateToken(Long userid,String username, String tableName, String role) {
        Token tokenEntity = this.selectOne(new EntityWrapper<Token>().eq("UserId", userid).eq("Role", role));
        //获取随机的32位字符串
        String token = CommonUtil.getRandomString(32);
        //获取token创建的时间为系统时间
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        //获取时间后的1小时
        cal.add(Calendar.HOUR_OF_DAY, 1);
        if(tokenEntity!=null) {
            tokenEntity.setToken(token);//将生成的随机字符串设置为token
            tokenEntity.setExpiratedTime(cal.getTime());//将系统时间作为token的时间
            this.updateById(tokenEntity);
        } else {
            this.insert(new Token(userid,username, tableName, role, token, cal.getTime()));
        }
        System.out.println(token);//仅测试使用
        return token;
    }

    @Override
    public Token getTokenEntity(String token) {
        Token tokenentity =this.selectOne(new EntityWrapper<Token>().eq("token", token));
        if (tokenentity == null || tokenentity.getExpiratedTime().getTime()< new Date().getTime()){
            return null;
        }
        return tokenentity;
    }


}
